﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using University.Workshop.Business;
using University.Workshop.DataAccess;
using University.Workshop.Model;

namespace University.Workshop.WebApp
{
    public partial class ViewTicket : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            if (!IsPostBack)
            {
                long ticketId=-1;
                if (Request.QueryString["ticketId"]!=null)
                    ticketId = long.Parse(Request.QueryString["ticketId"].ToString());
                if (ticketId != -1)
                {
                    Ticket ticket = TicketDataAccess.GetTicketById(ticketId);
                    if (ticket == null)
                        Response.Write("<script>if(window.history.length>1){history.back();} else {window.location.href = 'Default.aspx';}</script>");
                    else
                    {
                        bool isWebMaster = WebmasterManager.IsWebmaster(User.Identity.Name);
                        if (TicketManager.UserIsTheOwnerOfTicket(User.Identity.Name, ticket.Id) || isWebMaster)
                        {
                            MultiViewTicketInfo.ActiveViewIndex = 0;
                            IssueTitle.InnerText = ticket.IssueTitle;
                            txtContent.Text = ticket.Description;
                            Product prod = TicketDataAccess.GetProductByTicketId(ticket.Id);
                            ProductName.InnerText = prod.Name;
                            ProductName.HRef = "ProductSelected.aspx?ProductID=" + prod.ProductId;
                            LblPriority.Text = ticket.Priority.ToString();
                            LblStatus.Text = ticket.Status.ToString();
                            LblTicketDate.Text = ticket.Date.ToShortDateString();
                            string userName =
                                UserDataAccess.GetUserById(OrderDataAccess.GetOrderByIdOfOrder(ticket.OrderId).BuyerId).ContactInformation.Email;
                            if(userName==User.Identity.Name)
                                LinkUser.Text = "You!";
                            else LinkUser.Text = userName;
                            LinkUser.ToolTip = userName;
                            LinkUser.PostBackUrl = "UserProfile.aspx?user=" +userName;
                            dataListReplies.DataSource = TicketDataAccess.GetAllTicketReplies(ticket.Id);
                            dataListReplies.DataBind();
                            MultiViewReplies.ActiveViewIndex = dataListReplies.Items.Count != 0 ? 0 : 1;
                            MultiViewReply.ActiveViewIndex = ticket.Status == TicketStatus.Closed ? 1 : 0;
                            if (isWebMaster && ticket.Status!=TicketStatus.Closed)
                            {
                                drpDwnEditStatus.Items.Add(new ListItem{Value = "0", Text = ticket.Status.ToString(), Selected = true});
                                drpDwnEditStatus.Items.Add(new ListItem { Value = "1", Text = "Closed" });
                                LblStatus.Visible = false;
                                drpDwnEditStatus.Visible = true;
                            }
                            else
                            {
                                LblStatus.Visible = true;
                                drpDwnEditStatus.Visible = false;
                            }
                            if (isWebMaster)
                            {
                                if (!WebmasterDataAccess.GetWebmasterByUserId(UserDataAccess.GetUserByEmail(User.Identity.Name).Id).CanRespondTickets)
                                    MultiViewTicketInfo.ActiveViewIndex = 1;
                            }
                        }
                        else
                        {
                            MultiViewTicketInfo.ActiveViewIndex = 1;
                        }
                    }
                }
                else Response.Write("<script>if(window.history.length>1){history.back();} else {window.location.href = 'Default.aspx';}</script>");
            }
        }

        public string GetUser(object userIdOb)
        {
            long userId = long.Parse(userIdOb.ToString());
            return UserDataAccess.GetUserById(userId).ContactInformation.Email;
        }

        public string GetLinkUser(object userIdOb)
        {
            long userId = long.Parse(userIdOb.ToString());
            return "UserProfile.aspx?user="+UserDataAccess.GetUserById(userId).ContactInformation.Email;
        }

        public string FormatReply(object reply)
        {
            string[] splitWords = reply.ToString().Split(' ');
            StringBuilder formatedReply = new StringBuilder();
            foreach (string splitWord in splitWords)
            {
                if (splitWord.Length>80)
                {
                    int count = splitWord.Length/80;
                    for (int i = 0; i < count; i++)
                    {
                        formatedReply.Append(splitWord.Substring(80*i, 80));
                        formatedReply.Append("\n");   
                    }
                    formatedReply.Append(splitWord.Substring(count*80, splitWord.Length - 1 - (count*80)));
                }
                else
                {
                    formatedReply.Append(splitWord);
                    formatedReply.Append(" ");
                }
            }  
            formatedReply.Replace("&","&amp;");
            formatedReply.Replace("  ", " &nbsp;");
            formatedReply.Replace(">", "&gt;");
            formatedReply.Replace("<", "&lt;");
            formatedReply.Replace("\n", "</br>");
            return formatedReply.ToString();
        }

        protected void btnSendReply_Click(object sender, EventArgs e)
        {
            long ticketId = -1;
            if (Request.QueryString["ticketId"]!=null)
                    ticketId = long.Parse(Request.QueryString["ticketId"].ToString());
            if (ticketId != -1)
            {
                TicketManager.RespondTicket(ticketId, User.Identity.Name, txtReply.Text);
                dataListReplies.DataSource = TicketDataAccess.GetAllTicketReplies(ticketId);
                dataListReplies.DataBind();
                txtReply.Text = "";
                MultiViewReplies.ActiveViewIndex = dataListReplies.Items.Count != 0 ? 0 : 1;
                if (User.Identity.Name != LinkUser.Text && LblStatus.Text=="New" && WebmasterManager.IsWebmaster(User.Identity.Name))
                {
                    Ticket ticket = TicketDataAccess.ChangeTicketStatus(ticketId,TicketStatus.InProcess);
                    if (ticket.Status != TicketStatus.Closed)
                    {
                        drpDwnEditStatus.Items.Clear();
                        drpDwnEditStatus.Items.Add(new ListItem { Value = "0", Text = ticket.Status.ToString(), Selected = true });
                        drpDwnEditStatus.Items.Add(new ListItem { Value = "1", Text = "Closed" });
                        LblStatus.Visible = false;
                        drpDwnEditStatus.Visible = true;
                    }
                    else
                    {
                        LblStatus.Visible = true;
                        drpDwnEditStatus.Visible = false;
                    }
                }
            }
        }

        protected void Page_PreInit(Object sender, EventArgs e)
        {
            if (WebmasterManager.IsWebmaster(User.Identity.Name))
            {
                Page.MasterPageFile = "~/WebMasterCP.Master";
            }
            else
            {
                Page.MasterPageFile = "~/UserCP.Master";
            }
        }

        protected void drpDwnEditStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (drpDwnEditStatus.SelectedIndex==1)
            {
                btnConfirmClose.Visible = true;
            }
            else
            {
                btnConfirmClose.Visible = false;
            }
        }

        protected void btnConfirmClose_Click(object sender, EventArgs e)
        {
            long ticketId = -1;
            if (Request.QueryString["ticketId"]!=null)
                    ticketId = long.Parse(Request.QueryString["ticketId"].ToString());
            if (ticketId != -1)
            {
                TicketDataAccess.ChangeTicketStatus(ticketId, TicketStatus.Closed);
                Response.Redirect("ViewTicket.aspx?ticketId="+ticketId);
            }
        }
    }
}